package com.thread.demo.usage.suspend;

/**
 * 多线程中可以使用suspend暂停线程,使用resume恢复线程
 * suspend和resume方法的缺点，使用不当会造成公共对象的独占和数据不同步
 */
public class SuspendDemo extends Thread {
    private long i;

    synchronized public void printString() {
        System.out.println("begin:" + Thread.currentThread().getName());
        if (Thread.currentThread().getName().equals("a")) {
            System.out.println("a线程永远suspend了");
            Thread.currentThread().suspend();
        }
        System.out.println("end:" + Thread.currentThread().getName());
    }

    public long getI() {
        return i;
    }

    @Override
    public void run() {
        super.run();
        while (i < 500000) {
            i++;
            System.out.println(i);
        }
    }

    public static void main(String[] args) throws InterruptedException {
        /*SuspendDemo suspendDemo = new SuspendDemo();
        suspendDemo.start();
        Thread.sleep(5000);
        suspendDemo.suspend();
        System.out.println("暂停A:" + suspendDemo.getI());
        Thread.sleep(5000);
        System.out.println("暂停A:" + suspendDemo.getI());
        suspendDemo.resume();*/

        //suspend和resume方法的缺点，使用不当会造成公共对象的独占
        //线程a和b都调用实例busy的方法，但是a线程调用的时候暂停了，导致线程b不能调用
        SuspendDemo busy = new SuspendDemo();
        Thread a = new Thread() {
            @Override
            public void run() {
                super.run();
                busy.printString();
            }
        };
        a.setName("a");
        a.start();
        Thread.sleep(2000);
        Thread b = new Thread() {
            @Override
            public void run() {
                super.run();
                busy.printString();
            }
        };
        b.setName("b");
        b.start();

    }
}
